﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Morphine.Media
{
    public class MediaInfo
    {
        public string Title { get; set; }
        public string Artist { get; set; }
        public string Album { get; set; }
        public string Cover { get; set; }
        public string Duration { get; set; }
        public string Type { get; set; }
        public string File { get; set; }
        public int Index { get; set; }

        public static MediaInfo GetInfo(WMPLib.IWMPMedia media, bool getCover = true)
        {
            var info = new MediaInfo();
            if (media != null)
            {
                info.Title = media.getItemInfo("Title");
                info.Album = media.getItemInfo("Album");
                info.Artist = media.getItemInfo("Artist");
                info.Type = media.getItemInfo("MediaType");
                info.File = media.getItemInfo("SourceURL");
                info.Duration = media.durationString;
                var index = media.getItemInfo("PlaylistIndex");
                if (!string.IsNullOrEmpty(index))
                    info.Index = Convert.ToInt32(index);

                if (getCover)
                {
                    // look for album art
                    var dir = Path.GetDirectoryName(media.sourceURL);
                    if (dir != null && Directory.Exists(dir))
                    {
                        var artPaths = Directory.GetFiles(dir, "AlbumArt_*Large.jpg");

                        if (artPaths.Length == 0)
                            artPaths = Directory.GetFiles(dir, "Folder.jpg");
                        if (artPaths.Length == 0)
                            artPaths = Directory.GetFiles(dir, "cover.jpg");
                        if (artPaths.Length == 0)
                            artPaths = Directory.GetFiles(dir, "AlbumArt*.jpg");
                        if (artPaths.Length == 0)
                            artPaths = Directory.GetFiles(dir, "Album*.jpg");
                        if (artPaths.Length == 0)
                            artPaths = Directory.GetFiles(dir, "*.jpg");

                        if (artPaths.Length > 0)
                        {
                            info.Cover = artPaths[0];
                        }
                    }
                }

                return info;
            }
            return null;
        }
    }
}
